package com.ask.service.businessService.impl;

import com.ask.dto.Result;
import com.ask.entity.SeckillVoucher;
import com.ask.entity.VoucherOrder;
import com.ask.entity.VoucherOrderMessage;
import com.ask.mapper.VoucherOrderMapper;
import com.ask.service.businessService.ISecKillVoucherService;
import com.ask.service.businessService.IVoucherOrderService;
import com.ask.service.businessService.IVoucherService;
import com.ask.threadlocals.UserHolder;
import com.ask.utils.RedisIdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Service
@Slf4j
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {
    @Autowired
    private IVoucherService voucherService;
    @Autowired
    private ISecKillVoucherService secKillVoucherService;
    @Autowired
    private RedisIdWorker redisIdWorker;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    // 定义Lua脚本对象
    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;

    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill-mq.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    private IVoucherOrderService proxy;

    // 定义阻塞队列
    private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024 * 1024);

    // 定义线程池
    private static final ExecutorService SECKILL_ORDER_EXECUTOR = Executors.newSingleThreadExecutor();

    // 初始化时向线程池提交任务
//    @PostConstruct
//    private void init() {
//        SECKILL_ORDER_EXECUTOR.submit(new VoucherOrderHandler_Mq());
//    }

    // 定义线程池任务(异步优化版)
    private class VoucherOrderHandler implements Runnable {
        @Override
        public void run() {
            while (true) {
                try {
                    VoucherOrder order = orderTasks.take();
                    handleVoucherOrder(order);
                } catch (Exception e) {
                    log.error("处理订单异常", e);
                }
            }
        }
    }

//    // 定义线程池任务(消息队列优化版)
//    private class VoucherOrderHandler_Mq implements Runnable {
//        @Autowired
//        private RedisStreamUtil redisStreamUtil;
//        String queueName = "stream.orders";
//
//        @Override
//        public void run() {
//            while (true) {
//                try {
//                    log.info("从消息队列中读取消息...........");
//                    // 获取消息队列中的消息
//                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
//                            Consumer.from("g1", "c1"), // 指定消费者组和消费者
//                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
//                            StreamOffset.create(queueName, ReadOffset.lastConsumed()) // 从上次消费的位置继续读取
//                    );
//
//                    // 判断消息获取是否成功
//                    if (list == null || list.isEmpty())
//                        continue;
//
//                    // 解析消息中的订单信息
//                    MapRecord<String, Object, Object> record = list.get(0);
//                    Map<Object, Object> values = record.getValue();
//                    VoucherOrder order = BeanUtil.fillBeanWithMap(values, new VoucherOrder(), true);
//                    // 下单
//                    handleVoucherOrder(order);
//
//                    // ACK确认
//                    stringRedisTemplate.opsForStream().acknowledge(queueName, "g1", record.getId());
//                } catch (Exception e) {
//                    handlePendingList();
//                    log.error("处理订单异常", e);
//                }
//            }
//        }
//
//        private void handlePendingList() {
//            while (true) {
//                try {
//                    // 获取pending-list中的消息
//                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
//                            Consumer.from("g1", "c1"),
//                            StreamReadOptions.empty().count(1),
//                            StreamOffset.create(queueName, ReadOffset.from("0"))
//                    );
//
//                    // pending-list中没有异常消息,结束
//                    if (list == null || list.isEmpty())
//                        break;
//
//                    // 解析消息中的订单信息
//                    MapRecord<String, Object, Object> record = list.get(0);
//                    Map<Object, Object> values = record.getValue();
//                    VoucherOrder order = BeanUtil.fillBeanWithMap(values, new VoucherOrder(), true);
//                    // 下单
//                    handleVoucherOrder(order);
//
//                    // ACK确认
//                    stringRedisTemplate.opsForStream().acknowledge(queueName, "g1", record.getId());
//                } catch (Exception e) {
//                    log.error("处理pending-list订单异常", e);
//                }
//            }
//        }
//    }

    // 处理优惠卷订单
    private void handleVoucherOrder(VoucherOrder order) {
        Long userId = order.getUserId();
        RLock lock = redissonClient.getLock("lock:order:" + userId);
        boolean isLock = lock.tryLock();
        if (!isLock) {
            log.error("禁止重复下单");
            return;
        }
        try {
            proxy.createVoucherOrder_V2(order);
        } finally {
            lock.unlock();
        }
    }

    /**
     * 秒杀优惠卷（异步优化）
     *
     * @param voucherId
     * @return
     */
    public Result seckillVoucher_Opti(Long voucherId) {
        // 执行lua脚,判断是否有购买资格
        Long userId = UserHolder.getUser().getId();
        Long result = stringRedisTemplate.
                execute(SECKILL_SCRIPT, Collections.emptyList(),
                        voucherId.toString(),
                        userId.toString()
                );
        int r = result.intValue();
        // 没有购买资格
        if (r != 0) {
            return Result.fail(r == 1 ? "库存不足！" : " 禁止重复下单！");
        }

        // 有资格下单,把下单信息保存到阻塞队列
        // 生成订单id
        long orderId = redisIdWorker.nextId("order");
        // 封装订单信息
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setVoucherId(voucherId);
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(userId);
        // 放入阻塞队列
        orderTasks.add(voucherOrder);

        // 获取代理对象
        proxy = (IVoucherOrderService) AopContext.currentProxy();
        // 返回订单id
        return Result.success(orderId);
    }

    /**
     * 优惠卷秒杀-消息队列优化
     *
     * @param voucherId
     * @return
     */
    @Override
    public Result seckillVoucher_Mq(Long voucherId) {
        // 执行lua脚,判断是否有购买资格
        Long userId = UserHolder.getUser().getId();
        // 生成订单id
        long orderId = redisIdWorker.nextId("order");
        Long result = stringRedisTemplate.execute(SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(),
                userId.toString(),
                String.valueOf(orderId));
        int r = result.intValue();
        // 没有购买资格
        if (r != 0) {
            return Result.fail(r == 1 ? "库存不足！" : " 禁止重复下单！");
        }

        // 获取代理对象
        proxy = (IVoucherOrderService) AopContext.currentProxy();
        // 返回订单id
        return Result.success(orderId);
    }

    /**
     * 创建秒杀卷订单 V2
     *
     * @param order
     */
    @Override
    @Transactional
    public void createVoucherOrder_V2(VoucherOrder order) {
        Long userId = order.getUserId();
        Long voucherId = order.getVoucherId();
        // 查询当前用户是否已经抢过该秒杀卷
        Long count = query()
                .eq("user_id", userId)
                .eq("voucher_id", voucherId)
                .count();
        if (count > 0) {
            log.error("禁止重复下单！");
            return;
        }

        // 3. 跟新优惠劵表
        boolean success = secKillVoucherService.update().
                setSql("stock = stock - 1")
                .eq("voucher_id", voucherId)
                .gt("stock", 0)
                .update();
        if (!success) {
            log.error("库存不足！");
            return;
        }

        // 创建订单
        save(order);
    }

    /**
     * 秒杀优惠卷(分布式锁优化)
     *
     * @param voucherId
     * @return
     */
    @Override
    public Result seckillVoucher(Long voucherId) {
        // 1. 判断优惠卷是否过期
        SeckillVoucher seckillVoucher = secKillVoucherService.getById(voucherId);
        if (seckillVoucher == null) return Result.fail("优惠卷不存在！");

        LocalDateTime time = LocalDateTime.now();

        if (seckillVoucher.getBeginTime().isAfter(time)) return Result.fail("抢购还未开始！");

        if (time.isAfter(seckillVoucher.getEndTime())) return Result.fail("抢购已结束！");

        // 2，判断优惠卷库存是否充足
        Integer stock = seckillVoucher.getStock();
        if (stock < 1) return Result.fail("库存不足！");

        // 创建优惠卷
        Long userId = UserHolder.getUser().getId();

        RLock lock = redissonClient.getLock("lock:order:" + userId);
        boolean isLock = lock.tryLock();
        if (!isLock) {
            return Result.fail("禁止重复下单！");
        }

        try {
            IVoucherOrderService proxy = (IVoucherOrderService) AopContext.currentProxy();
            return proxy.createVoucherOrder(voucherId);
        } finally {
            lock.unlock();
        }

    }

    /**
     * 优惠卷秒杀-普通版本
     *
     * @param voucherId
     * @return
     */
    @Transactional
    public Result seckillVoucher_normal(Long voucherId, Long userId) {
        // Lua脚本判断资格
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(),
                userId.toString()
        );
        int r = result.intValue();
        if (r != 0) {
            return Result.fail(r == 1 ? "库存不足！" : "禁止重复下单!");
        }

        // 创建订单
        Long orderId = redisIdWorker.nextId("order"); // 生成订单id

        // 跟新优惠卷库存
        boolean success = secKillVoucherService.update()
                .setSql("stock = stock - 1")
                .eq("voucher_id", voucherId)
                .gt("stock", 0)
                .update();
        if (!success) {
            log.error("库存不足！");
            return Result.fail("库存不足！");
        }

        // 新增订单表
        VoucherOrder order = VoucherOrder.builder()
                .id(orderId)
                .userId(userId)
                .voucherId(voucherId)
                .build();

        save(order);
        return Result.success();
    }

    /**
     * 优惠卷秒杀（Kafka-Mq优化）
     *
     * @param voucherId
     * @return
     */

    @Autowired
    private KafkaTemplate<String, VoucherOrderMessage> kafkaTemplate;

    public Result seckillVoucher_KafkaMq(Long voucherId,Long userId) {
        // Lua脚本判断资格
        //Long userId = UserHolder.getUser().getId();
        Long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(),
                userId.toString()
        );
        int r = result.intValue();
        if (r != 0) {
            return Result.fail(r == 1 ? "库存不足！" : "禁止重复下单!");
        }

        // 订单消息
        VoucherOrderMessage message = VoucherOrderMessage.builder()
                .userId(userId)
                .voucherId(voucherId).build();

        // 发送消息到Kafka
        try {
            kafkaTemplate.send("voucher-order", message);
        } catch (Exception ex) {
            rollbackStock(voucherId, userId);
            log.error("消息发送异常，错误消息：{}", ex.getMessage());
        }
        return Result.success("下单成功！");
    }

    /**
     * 回滚库存
     *
     * @param voucherId
     * @param userId
     */
    private void rollbackStock(Long voucherId, Long userId) {
        String stockKey = "seckill:stock:" + voucherId;
        String orderKey = "seckill:order:" + voucherId;

        stringRedisTemplate.opsForValue().increment(stockKey, 1); // 恢复库存
        stringRedisTemplate.opsForSet().remove(orderKey, userId.toString()); // 移除用户购买记录
    }


    /**
     * 创建优惠卷订单
     *
     * @param voucherId
     * @return
     */
    @Transactional
    @Override
    public Result createVoucherOrder(Long voucherId) {
        Long userId = UserHolder.getUser().getId();
        // 查询当前用户是否已经抢过该秒杀卷
        Long count = query().eq("user_id", userId).eq("voucher_id", voucherId).count();
        if (count > 0) return Result.fail("禁止重复抢购！");

        // 3. 跟新优惠劵表
        boolean success = secKillVoucherService.update().setSql("stock = stock - 1").eq("voucher_id", voucherId).gt("stock", 0).update();
        if (!success) return Result.fail("库存不足！ (in createOrder)");

        // 4. 跟新优惠卷订单表
        VoucherOrder voucherOrder = VoucherOrder.builder().id(redisIdWorker.nextId("order")).userId(UserHolder.getUser().getId()).pay_type(1).status(1).voucherId(voucherId).build();
        save(voucherOrder);
        return Result.success(voucherOrder.getId());
    }
}
